function SiemensFileStructure2OSIRIX(PathName,OPathName,EnrollID)

% this function runs a script identify the siemens file structure directory
% and pull all the file SeriesDescriptions, SeriesNumbers, and
% InstanceNumbers to create a directory called [SeriesDescription '_'
% Series Number] and copies and renames the files into this new folder
% using the Instance number and Series number.

% This also anonymizes all PHI information, keeping those fields id'd in
% keepFields (if AnonFlag is 1)

% TODO: recurse subdirectories when I choose a 10000000 file and ignore
% dicomdir file, lest the program get too confused

clc;
currentdir = pwd;
if nargin==1
    disp('Function call needs 2 folder inputs')
    return
elseif nargin < 1
    % Identify folder where Siemens File structure is located
    PathName    = uigetdir(currentdir,'Select Siemens patient folder');
    if PathName == 0
        disp('The user canceled this function')
        return
    end
    % Identify folder location where OSIRIX file structure is to be written
    OPathName   = uigetdir(currentdir,'Select Folder to Write Osirix Format');
    if OPathName == 0
        disp('The user canceled this function')
        return
    end
elseif nargin == 2
    EnrollID = 'removed';
end

FileDir        = dir(PathName);
FileCount      = size(FileDir,1);
cd(PathName);
LastSeriesDesc = ' ';
LastSeriesNumb = 0  ;
CopyCount      = 0  ;
AnonFlag       = 0  ;
h              = waitbar(0,'Writing OSIRIX Formatted Files...','Position',[400 450 275 50]);

for i = 1:FileCount    
    if (length(FileDir(i).name) >= 3) && (FileDir(i).isdir < 1)         
        ImageInfo   = dicominfo([PathName '\' FileDir(i).name]);
        [X, map]    = dicomread(ImageInfo);
        %Get and modify folder names  (remove invalid chars and spaces)
        NewestDesc  = ImageInfo.SeriesDescription;
        NewestDesc  = regexprep(NewestDesc,'<|>|:','');        % get rid of invalid characters '<' '>'        
        NewestDesc  = regexprep(NewestDesc,' - | -|- ','-'); % get rid of dash spaces
        NewestDesc  = regexprep(NewestDesc,' ','_');         % get rid of spaces
        NewestNumb  = ImageInfo.SeriesNumber;        
		if ~(strcmp(LastSeriesDesc, NewestDesc)) && (LastSeriesNumb ~= NewestNumb)          
            NewPath = [OPathName '\' num2str(NewestNumb) '_' NewestDesc ];    
            [status Msg MsgID] = mkdir(NewPath);           
            if status 
                disp(' ');
                disp(['Writing new directory: ' NewPath]);
                disp(MsgID);
            else
                disp(' ');
                disp(Msg);
                disp(['NewPath = ' NewPath])
                return
            end            
        end
        if isfield(ImageInfo,'InstanceNumber')
            NewFile = ['IM-' num2str(ImageInfo.SeriesNumber,'%04.0f')...
                '-' num2str(ImageInfo.InstanceNumber,'%04.0f') '.dcm'];
        else
            NewFile = ['IM-' num2str(ImageInfo.SeriesNumber,'%04.0f'), '-' num2str(dicomuid) '.dcm']
        end
        OldFile = [FileDir(i).name] ;
        if AnonFlag
            % remove patient specific information...
            % keep ImageInfo.PatientSex, ImageInfo.PatientAge, ImageInfo.PatientWeight
            ImageInfo = removePHI(ImageInfo);
            if (~isempty(map))
                dicomwrite(X, map, [NewPath '\' NewFile], ImageInfo, 'createmode', 'copy');
            else
                dicomwrite(X, [NewPath '\' NewFile], ImageInfo, 'createmode', 'copy');
            end
            CopyCount = CopyCount + 1;
            disp(['   ' num2str(CopyCount) ' copied: ..\' FileDir(i).name ' to ' NewPath '\' NewFile]);
        else     
            [status Msg MsgID] = copyfile([PathName '\' OldFile], [NewPath '\' NewFile]);
            if status
                CopyCount = CopyCount + 1;
                disp(['   ' num2str(CopyCount) ' copied: ..\' FileDir(i).name ' to ' NewPath '\' NewFile]);
                disp(MsgID);
            else
                disp(Msg);
                disp(['OldFilePath = ' PathName '\' OldFile])
                disp(['NewFilePath = ' NewPath '\' NewFile])
                return;
            end
        end
        
        LastSeriesNumb  = ImageInfo.SeriesNumber;
        LastSeriesDesc  = ImageInfo.SeriesDescription;
%         LastInstanceNum = ImageInfo.InstanceNumber;
        
    end
       
    waitbar(i/FileCount, h);
    
end
close(h)


    function ImageInfo = removePHI(ImageInfo)

        if isfield(ImageInfo.PatientName,'FamilyName')
            ImageInfo.PatientName.FamilyName = EnrollID{1};
        end
        if isfield(ImageInfo.PatientName,'GivenName')
            ImageInfo.PatientName.GivenName  = '';
        end
        if isfield(ImageInfo.PatientName,'MiddleName')
            ImageInfo.PatientName.MiddleName = '';
        end
        if isfield(ImageInfo,'PatientID')
            ImageInfo.PatientID              = '';
        end
        if isfield(ImageInfo,'PatientBirthDate')
            ImageInfo.PatientBirthDate       = '';
        end
        if isfield(ImageInfo,'PatientAddress')
            ImageInfo.PatientAddress         = 'removed';
        end
        if isfield(ImageInfo,'InstitutionName')
            ImageInfo.InstitutionName        = 'removed';
        end
        if isfield(ImageInfo,'InstitutionAddress')
            ImageInfo.InstitutionAddress     = 'removed';
        end
        if isfield(ImageInfo,'InstitutionAddress')
            ImageInfo.InstitutionAddress     = 'removed';
        end
        if isfield(ImageInfo,'InstitutionAddress')
            ImageInfo.InstitutionAddress     = 'removed';
        end
        if isfield(ImageInfo,'ReferringPhysicianName')
            ImageInfo = rmfield(ImageInfo,'ReferringPhysicianName');
        end

    end

end